﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Text;
using elmah2.core.config;
using elmah2.core.interfaces;
using elmah2.core.data;

namespace elmah2.Viewer
{
  /// <summary>
  /// Summary description for $codebehindclassname$
  /// </summary>
  [WebService(Namespace = "http://tempuri.org/")]
  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  public class GetErrors : IHttpHandler
  {
    public void ProcessRequest(HttpContext context)
    {
      string logger = GetFormData("logger", context);

      if (!string.IsNullOrEmpty(logger))
      {
        int page;
        int size;
        int? app = null;
        int appTemp;

        if (!int.TryParse(GetFormData("page", context), out page))
          page = 1;

        if (!int.TryParse(GetFormData("rp", context), out size))
          size = 40;

        if (int.TryParse(GetFormData("app", context), out appTemp))
          app = appTemp > 0 ? new Nullable<int>(appTemp) : null;

        IErrorLogger eLogger = Logger.GetLogger(logger);
        ErrorData errors = eLogger.GetErrors(page, size, app);
        JavaScriptSerializer json = new JavaScriptSerializer();

        context.Response.Write(json.Serialize(new
          {
            page = page,
            total = errors.TotalErrors,
            rows = from i
                   in errors.Errors
                   select new
                    {
                      id = i.ID,
                      cell = new string[]
                        {
                          i.Host, i.Application, i.Code, string.Format("<a href='/ViewError.aspx?error={0}&logger={1}' alt='View Details'>{2}</a>", HttpUtility.UrlEncode(i.ID), HttpUtility.UrlEncode(logger), i.Error), i.Type, i.User, i.Date, i.Time
                        }
                    }
          }));
        context.Response.Flush();
        context.Response.End();
      }
    }

    public bool IsReusable
    {
      get
      {
        return false;
      }
    }

    private string GetFormData(string p, HttpContext context)
    {
      string value = "";
      foreach (string s in context.Request.Form.AllKeys)
      {
        if (s.Equals(p, StringComparison.InvariantCultureIgnoreCase))
        {
          value = context.Request.Form[p];
          break;
        }
      }
      return value;
    }
  }
}
